import { useRef, useState } from 'react';

import { useClickAway, useControllableValue } from 'ahooks';
import { Col, Input, InputProps, Radio, RadioProps, Row, RowProps } from 'antd';
import { ColProps } from 'antd/lib';
import cs from 'classnames';

import styles from './index.module.scss';

export type SearchInputProps = Omit<InputProps, 'value' | 'onChange'> & {
  typeList: RadioProps[];
  value?: Record<RadioProps['value'], string>;
  rowProps?: RowProps;
  colProps?: ColProps;
  onChange?: (e: SearchInputProps['value']) => void;
};

const SearchInput: React.FC<SearchInputProps> = ({
  typeList,
  className,
  rowProps,
  colProps,
  ...rest
}) => {
  const $wrap = useRef<HTMLDivElement>(null);
  const [value, setValue] = useControllableValue<SearchInputProps['value']>(rest, {
    defaultValue: typeList.reduce<SearchInputProps['value']>(
      (acc, cur) => ({ ...acc, [cur.value]: '' }),
      {}
    )
  });
  const [open, setOpen] = useState(false);
  const [searchType, setSearchType] = useState<RadioProps['value']>();

  const onChange: InputProps['onChange'] = (e) => {
    setValue({
      [searchType]: e.target.value
    });
  };

  const onFocus: SearchInputProps['onFocus'] = () => {
    setOpen(true);
    if (typeof searchType === 'undefined' && typeList.length) {
      setSearchType(typeList[0].value);
    }
  };

  useClickAway(() => {
    if (open) {
      setOpen(false);
      if (!value?.[searchType]) {
        setSearchType(undefined);
      }
    }
  }, $wrap);

  return (
    <div
      className={cs(styles['search-input-wrapper'], {
        [styles['open']]: open
      })}
      ref={$wrap}
    >
      <Input
        className={cs(styles['search-input'], className)}
        prefix={typeList.find((item) => item.value === searchType)?.children ?? '请输入'}
        allowClear
        placeholder={
          searchType
            ? (typeList.find((item) => item.value === searchType)?.children as string)
            : typeList.map((v) => v.children).join(' / ')
        }
        {...rest}
        value={value?.[searchType]}
        onChange={onChange}
        onFocus={onFocus}
        autoComplete="off"
      />
      <div className={styles['search-input-dropdown']}>
        <Radio.Group
          className={styles['search-input-type-list']}
          value={searchType}
          onChange={(e) => setSearchType(e.target.value)}
        >
          <Row gutter={[8, 8]} {...rowProps}>
            {typeList.map((item) => (
              <Col key={item.value} span={12} {...colProps}>
                <Radio value={item.value}>{item.children}</Radio>
              </Col>
            ))}
          </Row>
        </Radio.Group>
      </div>
    </div>
  );
};

export default SearchInput;
